//
//  CarpoolingViewController.m
//  cityStar
//
//  Created by joyban on 15-1-20.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "CarpoolingViewController.h"
#import "SingleTableView.h"
#import <CoreLocation/CoreLocation.h>
#import "selectDistrict.h"

#import "CarpoolingDetailViewController.h"

#import "CarpoolingListCell.h"

#import "SVPullToRefresh.h"
#import "CarpoolingListModel.h"
#import "CarpoolPublishViewController.h"
#import "LoginCityStarViewViewController.h"
#import "BaseNavController.h"
NSString *const carpoolingListCellID = @"CarpoolingListCellID";


@interface CarpoolingViewController ()<SingleTableViewDelegate,CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;

@property(weak,nonatomic) IBOutlet UIButton * SetoutCitybtn;
@property(weak,nonatomic) IBOutlet UIButton * SetoutTimebtn;
@property(weak,nonatomic) IBOutlet UIButton * CarpoolingTypebtn;
@property(weak,nonatomic) IBOutlet UITableView * CarpoolingTable;

@property(nonatomic,strong) NSMutableArray *cityArr;
@property (nonatomic,weak) IBOutlet UIImageView *SetoutCityImageView;
@property (strong, nonatomic) SingleTableView *SelectCityTableView;
@property (nonatomic, assign) BOOL isShowAddressList;

@property (nonatomic, weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *SetoutTimeImageView;
@property (strong, nonatomic) SingleTableView *SetoutTimeSingleTableView;

@property (nonatomic, weak) IBOutlet UIImageView *CarpoolingTypeImageView;
@property (strong, nonatomic) SingleTableView *CarpoolingTypeSingleTableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (nonatomic, weak) IBOutlet UILabel *nothinglabel;
@property (nonatomic, assign) NSString *strOrder;
@property (nonatomic, assign) NSString *strage;
@property (nonatomic, assign) NSString *strDistrict;
@property (nonatomic, assign) NSString *strDistrictid;

@end

@implementation CarpoolingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"拼车";
    [self addBackButton];
    [self setUpTableViews];
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithTitle:@"    发布" actionBlock:^{
        if (weakSelf.currentUser.nickname) {
        CarpoolPublishViewController *carpoolVC = [[CarpoolPublishViewController alloc]init];
        [weakSelf.navigationController pushViewController:carpoolVC animated:YES];
        }else{
            [weakSelf presentLoginViewController];
        }
    }];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddressStatues) name:@"isShowAddressList" object:nil];
    
    self.strOrder = @"";
    self.strDistrict = @"";
    self.strage = @"";
    
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
//    self.cityArr = @[@"附近",@"上海",@"北京",@"同城"];
//    self.areaArr = @[
//                     @[@"附近",@"500米",@"1000米",@"2000米",@"5000米"],
//                     @[@"徐家汇",@"人民广场",@"陆家嘴"],
//                     @[@"三里屯",@"亚运村",@"朝阳公园"],
//                     @[@"同城"],
//                     ];
//    self.currentAreaArr = _areaArr[0];
//    FSDropDownMenu *menu = [[FSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 36) andHeight:300];
//    menu.transformView = self.SetoutCityImageView;
//    menu.tag = 1001;
//    menu.dataSource = self;
//    menu.delegate = self;
//    [self.view addSubview:menu];
    self.cityArr = [[NSMutableArray alloc]init];
    [self.cityArr addObject:@"全部区域"];
    self.arrayRequest = [[NSMutableArray alloc]init];

    [self.CarpoolingTable addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [weakSelf webRequest_GetCarpoolingMore:NO];
        
    }];
    [self.CarpoolingTable addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetCarpoolingMore:YES];
        
    }];
    [self.CarpoolingTable triggerPullToRefresh];
}

- (void)webRequest_GetCarpoolingMore:(BOOL)isMore
{
    NSString *EndUrl = @"";
    NSString *postUrl = [NSString stringWithFormat:@"%@/type/%d/page/%d/mine/%d",KInterface_PublishList,0,isMore?self.page:0,0];
    EndUrl = postUrl;
    if(![self.strDistrict isEqualToString:@""])
    {
        EndUrl = [NSString stringWithFormat:@"%@/district/%@",EndUrl,self.strDistrictid];
        
    }
    if(![self.strOrder isEqualToString:@""])
    {
        NSString *strid = @"";
        if([self.strOrder isEqualToString:@"经济型"])
        {
            strid = @"0";
        }else if([self.strOrder isEqualToString:@"舒适型"]){
            strid = @"1";
        }
        else{
            strid = @"2";
        }
        EndUrl = [NSString stringWithFormat:@"%@/car_model/%@",EndUrl,strid];
    }
    if(![self.strage isEqualToString:@""])
    {
        NSString *strid = @"";
        if([self.strage isEqualToString:@"上下班拼车"])
        {
            strid = @"0";
        }else if([self.strage isEqualToString:@"单程旅行拼车"]){
            strid = @"1";
        }
        else{
            strid = @"2";
        }
        EndUrl = [NSString stringWithFormat:@"%@/carpool_type/%@",EndUrl,strid];
    }

    [HttpRequestManager getMethod:[EndUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][0][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][0][@"content"]];
            }
            [self.CarpoolingTable reloadData];
            if (self.arrayRequest.count == 0) {
                self.nothinglabel.hidden = NO;
            }else{
                self.nothinglabel.hidden = YES;
            }
        }
        if (isMore) {
            [self.CarpoolingTable.infiniteScrollingView stopAnimating];
        }else{
            [self.CarpoolingTable.pullToRefreshView stopAnimating];
        }
    }];
}


#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [self webRequest_citydataWithCityID:str];
        }else{
            
        }
    }];
}
-(void)webRequest_citydataWithCityID:(NSString *)sendeid
{
    NSString *getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,sendeid];
    [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            [[selectDistrict shardDistrictInfo]setClasscityArray:response[@"value"]];
            
            self.cityArr = [[NSMutableArray alloc]init];
            NSArray *array = [[NSArray alloc]init];
            array = [selectDistrict shardDistrictInfo].DistrictArray;
            
            [self.cityArr addObject:@"选择区域"];
            [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                [self.cityArr addObject:obj[@"name"]];
            }];
        }else{
            DLog(@"%@",errMsg);
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

-(void)changeAddressStatues
{
    self.isShowAddressList = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setUpTableViews
{
    [self.CarpoolingTable registerNib:[CarpoolingListCell nib] forCellReuseIdentifier:carpoolingListCellID];
}
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [CarpoolingListCell heightOfTableCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CarpoolingListCell *ListdetailCell = [tableView dequeueReusableCellWithIdentifier:carpoolingListCellID];
    CarpoolingListModel *carList = [CarpoolingListModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    ListdetailCell.selectionStyle = UITableViewCellSelectionStyleGray;
    [ListdetailCell setCityPollingData:carList];
    return ListdetailCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    CarpoolingListModel *carList = [CarpoolingListModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    CarpoolingDetailViewController *carpoolingViewController = [[CarpoolingDetailViewController alloc]init];
    carpoolingViewController.carModel = carList;
    carpoolingViewController.withchType = @"cityService";
    [self.navigationController pushViewController:carpoolingViewController animated:YES];
}

#pragma mark - Actions
-(IBAction)SetoutTime_atction:(id)sender
{

    if(self.SetoutTimebtn.selected == NO)
    {
        self.SetoutTimebtn.selected = YES;
    }else
    {
        self.SetoutTimebtn.selected = NO;
    }
    self.SetoutCitybtn.selected = NO;
    self.CarpoolingTypebtn.selected = NO;
    
    [self.SetoutTimeSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.SetoutTimeSingleTableView.dataArray = @[@"全部车型",@"经济型",@"舒适型",@"豪华型"];
}

-(IBAction)CarpoolingType_atction:(id)sender
{

    if(self.CarpoolingTypebtn.selected == NO)
    {
        self.CarpoolingTypebtn.selected = YES;
    }else
    {
        self.CarpoolingTypebtn.selected = NO;
    }
    self.SetoutCitybtn.selected = NO;
    self.SetoutTimebtn.selected = NO;
    
    [self.CarpoolingTypeSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.CarpoolingTypeSingleTableView.dataArray = @[@"全部类型",@"上下班拼车",@"单程旅行拼车",@"往返双程旅行拼车"];
}

-(IBAction)SetoutCity_action:(id)sender
{
    if(self.SetoutCitybtn.selected == NO)
    {
        self.SetoutCitybtn.selected = YES;
    }else
    {
        self.SetoutCitybtn.selected = NO;
    }
    self.SetoutTimebtn.selected = NO;
    self.CarpoolingTypebtn.selected = NO;
    
    [self.SelectCityTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.SelectCityTableView.dataArray = self.cityArr;
}

#pragma mark - singleTableViewDelegate
- (SingleTableView *)SelectCityTableView
{
    if (!_SelectCityTableView) {
        _SelectCityTableView = [[SingleTableView alloc] init];
        _SelectCityTableView.delegate = self;
        [self addChildViewController:_SelectCityTableView];
        [self.view addSubview:_SelectCityTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _SelectCityTableView.arrawImageView = self.SetoutCityImageView;
    }
    return _SelectCityTableView;
}

- (SingleTableView *)SetoutTimeSingleTableView
{
    if (!_SetoutTimeSingleTableView) {
        _SetoutTimeSingleTableView = [[SingleTableView alloc] init];
        _SetoutTimeSingleTableView.delegate = self;
        [self addChildViewController:_SetoutTimeSingleTableView];
        [self.view addSubview:_SetoutTimeSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _SetoutTimeSingleTableView.arrawImageView = self.SetoutTimeImageView;
    }
    return _SetoutTimeSingleTableView;
}

- (void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.SetoutCitybtn.selected = NO;
    self.SetoutTimebtn.selected = NO;
    self.CarpoolingTypebtn.selected = NO;
    if (tableView == self.SetoutTimeSingleTableView) {
        NSString *celltest = @[@"全部车型",@"经济型",@"舒适型",@"豪华型"][indexPath.row];
        self.strOrder = celltest;
        if([self.strOrder isEqualToString:@"全部车型"])
        {
            self.strOrder = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.SetoutTimebtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.SetoutTimebtn setTitle:celltest forState:UIControlStateNormal];
        }
    }else if (tableView == self.SelectCityTableView)
    {
        NSString *celltest = self.cityArr[indexPath.row];
        self.strDistrict = self.cityArr[indexPath.row];
        NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
        [array addObject:@""];
        if([self.strDistrict isEqualToString:@"选择区域"] == YES)
        {
            self.strDistrict = @"";
        }else{
            NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
            [array addObject:@""];
           
            self.strDistrictid = array[indexPath.row-1];
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.SetoutCitybtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.SetoutCitybtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    else
    {
        NSString *celltest = @[@"全部类型",@"上下班拼车",@"单程旅行拼车",@"往返双程旅行拼车"][indexPath.row];
        self.strage = celltest;
        if([self.strage isEqualToString:@"全部类型"])
        {
            self.strage = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.CarpoolingTypebtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.CarpoolingTypebtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    self.page = 1;
    [self webRequest_GetCarpoolingMore:NO];
}

- (SingleTableView *)CarpoolingTypeSingleTableView
{
    if (!_CarpoolingTypeSingleTableView) {
        _CarpoolingTypeSingleTableView = [[SingleTableView alloc] init];
        _CarpoolingTypeSingleTableView.delegate = self;
        [self addChildViewController:_CarpoolingTypeSingleTableView];
        [self.view addSubview:_CarpoolingTypeSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _CarpoolingTypeSingleTableView.arrawImageView = self.CarpoolingTypeImageView;
    }
    return _CarpoolingTypeSingleTableView;
}
#pragma mark - reset button size

//-(void)resetItemSizeBy:(NSString*)str{
//    //    [self.btnAddress setTitleColor:[UIColor colorWithWhite:0.580 alpha:1.000] forState:UIControlStateNormal];
//    if (str.length >= 5) {
//        NSString *btnTitle = [NSString stringWithFormat:@"%@..",[str substringWithRange:NSMakeRange(0, 4)]];
//        [self.SetoutCitybtn setTitle:btnTitle forState:UIControlStateNormal];
//    }else{
//        [self.SetoutCitybtn setTitle:str forState:UIControlStateNormal];
//    }
//}

#pragma mark - FSDropDown datasource & delegate

//- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
//    if (tableView == menu.rightTableView) {
//        return _cityArr.count;
//    }else{
//        return _currentAreaArr.count;
//    }
//}
//- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (tableView == menu.rightTableView) {
//        
//        return _cityArr[indexPath.row];
//    }else{
//        return _currentAreaArr[indexPath.row];
//    }
//}
//
//
//- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(tableView == menu.rightTableView){
//        _currentAreaArr = _areaArr[indexPath.row];
//        [menu.leftTableView reloadData];
//    }else{
//        self.isShowAddressList = NO;
//        self.SetoutCitybtn.selected = NO;
//        self.SetoutTimebtn.selected = NO;
//        self.CarpoolingTypebtn.selected = NO;
//        [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
//    }
//    
//}

-(void)cancleTabelView
{
    self.SetoutTimebtn.selected = NO;
    self.SetoutCitybtn.selected = NO;
    self.CarpoolingTypebtn.selected = NO;
}

-(void)senderCancle
{
    self.SetoutTimebtn.selected = NO;
    self.SetoutCitybtn.selected = NO;
    self.CarpoolingTypebtn.selected = NO;
}

#pragma mark - IsJumpToLoginViewController
-(void)presentLoginViewController
{
    LoginCityStarViewViewController *loginCityStarVC = [[LoginCityStarViewViewController alloc]init];
    BaseNavController *baseloginNav = [[BaseNavController alloc] initWithRootViewController:loginCityStarVC];
    [self presentViewController:baseloginNav animated:YES completion:^{
    }];
}

@end
